package com.tdam2011.grupo02.ui;

import java.util.Date;
import java.util.LinkedList;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemLongClickListener;

import com.tdam2011.grupo02.R;
import com.tdam2011.grupo02.compatibility.ActionBarFragmentActivity;
import com.tdam2011.grupo02.connectivity.ConnectivityInformationSingleton;
import com.tdam2011.grupo02.data.DatabaseHelperSingleton;
import com.tdam2011.grupo02.data.LogsController;
import com.tdam2011.grupo02.data.OnSendingInterface;
import com.tdam2011.grupo02.domain.MensajeWeb;
import com.tdam2011.grupo02.widget.popup.ActionItem;
import com.tdam2011.grupo02.widget.popup.QuickAction;

public class MsgwConversationListActivity extends ActionBarFragmentActivity
		implements OnClickDialogFragmentInterface, OnSendingInterface {

	private ListView lv;
	private MsgwConversationAdapter adapter;
	private String nombre;
	private Uri imgUri;
	private QuickAction msgwPopup;
	private LinearLayout lyMsgwEdit;
	private EditText txtMensajeWeb;
	private Button btnSend;
	private Button btnCancel;
	private int positionAdapter;
	private MensajeWeb msgw;
	private MsgwConversationAsyncTask MensajeWebConversationAsyncTask;
	private LogsController controller;
	private NotificationManager notificationManager;
	private Context context;
	private int NOTIFICATION = R.string.sendMsgwNotificationTitle;
	private Notification notification;

	public static int MensajeWeb_TYPE_OTHER = 1;
	public static int MensajeWeb_TYPE_USER = 2;

	private static final int POPUP_ACTION_ITEM_SEND = 11;
	private static final int POPUP_ACTION_ITEM_DELETE = 13;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.selected_msg_conversation);

		createMensajeWebPopup();
		Bundle data = getIntent().getExtras();
		nombre = data.getString("name");
		imgUri = (Uri) data.get("imgUri");

		setTitle(nombre);

		// ((ImageView) findViewById(R.id.imgContacto)).setImageURI(imgUri);

		context = this;

		adapter = new MsgwConversationAdapter(context);
		lv = (ListView) findViewById(R.id.listMsg);
		lv.setAdapter(adapter);
		lv.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				positionAdapter = position;

				int firstPosition = lv.getFirstVisiblePosition()
						- lv.getHeaderViewsCount();
				int wantedChild = positionAdapter - firstPosition;

				View v = (View) lv.getChildAt(wantedChild);

				msgwPopup.show(v);
				return false;
			}
		});

		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				MensajeWeb aux = (MensajeWeb) adapter.getItem(position);

				if (aux.getContactLocation() != null) {
					Intent intent = new Intent(
							MsgwConversationListActivity.this,
							ContactMapActivity.class);
					intent.putExtra("latitude", aux.getContactLocation()
							.getLatitud());
					intent.putExtra("longitude", aux.getContactLocation()
							.getLongitude());
					intent.putExtra("address", aux.getContactLocation()
							.getAddress());

					context.startActivity(intent);
				}
			}

		});

		controller = new LogsController(this);
		notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
	}

	@Override
	protected void onResume() {
		initData();
		super.onResume();
	}

	private void initData() {
		MensajeWebConversationAsyncTask = new MsgwConversationAsyncTask();
		MensajeWebConversationAsyncTask.execute(nombre);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.options_menu_msgw_conversation, menu);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
		case R.id.menu_msgw_conversation_edit:
			editMensajeWeb();
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	private class MsgwConversationAsyncTask extends
			AsyncTask<String, String, LinkedList<MensajeWeb>> {

		@Override
		protected LinkedList<MensajeWeb> doInBackground(String... params) {
			return controller.getWebMessagesConversation(params[0]);
		}

		@Override
		protected void onPostExecute(LinkedList<MensajeWeb> result) {
			adapter.add(result);
			adapter.notifyDataSetChanged();
			
			super.onPostExecute(result);
		}
	}

	class MsgwConversationAdapter extends BaseAdapter {

		private Context context;
		private LinkedList<MensajeWeb> mensajesWeb;
		private LayoutInflater inflater;
		private Holder holder;

		public MsgwConversationAdapter(Context context) {
			this.context = context;
			this.mensajesWeb = new LinkedList<MensajeWeb>();
			inflater = LayoutInflater.from(MsgwConversationListActivity.this);
		}

		public void add(LinkedList<MensajeWeb> mensajesWeb) {
			if (mensajesWeb != null)
				this.mensajesWeb = mensajesWeb;
		}

		@Override
		public int getCount() {
			return mensajesWeb.size();
		}

		@Override
		public Object getItem(int position) {
			return mensajesWeb.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup arg2) {
			final MensajeWeb info = (MensajeWeb) getItem(position);

			if (convertView == null) {
				holder = new Holder();

				if (info.getTipo() == MensajeWeb.TYPE_RECEIVED) {
					convertView = inflater.inflate(
							R.layout.item_conversation_sms_in, null);
				} else {
					convertView = inflater.inflate(
							R.layout.item_conversation_sms_out, null);
				}

				holder.type = info.getTipo();
				holder.fecha = (TextView) convertView.findViewById(R.id.sFecha);
				holder.mensaje = (TextView) convertView
						.findViewById(R.id.sMensaje);
				holder.address = (TextView) convertView
						.findViewById(R.id.sAddress);

				convertView.setTag(holder);
			} else {
				holder = (Holder) convertView.getTag();
				if (holder.type != info.getTipo()) {					

					if (info.getTipo() == MensajeWeb.TYPE_RECEIVED) {
						convertView = inflater.inflate(
								R.layout.item_conversation_sms_in, null);
					} else {
						convertView = inflater.inflate(
								R.layout.item_conversation_sms_out, null);
					}

					holder = new Holder();
					holder.type = info.getTipo();
					holder.fecha = (TextView) convertView
							.findViewById(R.id.sFecha);
					holder.mensaje = (TextView) convertView
							.findViewById(R.id.sMensaje);
					holder.address = (TextView) convertView
							.findViewById(R.id.sAddress);
					convertView.setTag(holder);
				}
			}

			Date installDate = new Date(info.getFecha());
			String timeFormat = DateFormat.getTimeFormat(context).format(
					installDate);
			String dateFormat = DateFormat.getDateFormat(context).format(
					installDate);

			holder.fecha.setText(dateFormat + " " + timeFormat);
			holder.mensaje.setText(info.getMensaje());

			if (info.getContactLocation() != null) {
				holder.address.setVisibility(View.VISIBLE);
				holder.address.setText(info.getContactLocation().getAddress());

			} else {
				holder.address.setVisibility(View.GONE);
			}

			return convertView;
		}

		class Holder {
			private TextView fecha;
			private TextView mensaje;
			private TextView address;
			private int type;
		}
	}

	public void createMensajeWebPopup() {
		ActionItem enviarItem = new ActionItem(POPUP_ACTION_ITEM_SEND,
				getString(R.string.actionSend), getResources().getDrawable(
						android.R.drawable.ic_menu_send));
		ActionItem eliminarItem = new ActionItem(POPUP_ACTION_ITEM_DELETE,
				getString(R.string.actionDelete), getResources().getDrawable(
						android.R.drawable.ic_menu_delete));

		msgwPopup = new QuickAction(this);

		msgwPopup.addActionItem(enviarItem);
		msgwPopup.addActionItem(eliminarItem);

		msgwPopup
				.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
					@Override
					public void onItemClick(QuickAction quickAction, int pos,
							int actionId) {
						msgw = (MensajeWeb) adapter.getItem(positionAdapter);

						switch (actionId) {
						case POPUP_ACTION_ITEM_SEND:
							// ContactActionControllerSingleton
							// .getInstance(MsgwConversationListActivity.this)
							// .getContactActionController()
							// .sendMensajeWeb(MensajeWeb.getNumero(),
							// MensajeWeb.getMensaje());
							break;

						case POPUP_ACTION_ITEM_DELETE:
							showDialog();
							break;
						}
					}
				});

		msgwPopup.setOnDismissListener(new QuickAction.OnDismissListener() {
			@Override
			public void onDismiss() {
			}
		});

	}

	private void editMensajeWeb() {
		if (lyMsgwEdit == null) {
			lyMsgwEdit = (LinearLayout) findViewById(R.id.lyMsgEdit);
			txtMensajeWeb = (EditText) findViewById(R.id.txtMsgContent);
			btnSend = (Button) findViewById(R.id.btnMsgSend);
			btnCancel = (Button) findViewById(R.id.btnMsgCancel);

			btnSend.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					sendWebMessage();
				}
			});

			btnCancel.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					lyMsgwEdit.setVisibility(View.GONE);
				}
			});
		}

		if (lyMsgwEdit.getVisibility() == View.GONE)
			lyMsgwEdit.setVisibility(View.VISIBLE);
		else
			lyMsgwEdit.setVisibility(View.GONE);
	}

	// Dialog Fragment

	private void showInternetConnectionDialog() {
		DialogFragment newFragment = MyAlertDialogFragment.newInstance(
				new OnClickDialogFragmentInterface() {

					@Override
					public void doPositiveClick() {
					}

					@Override
					public void doNegativeClick() {

					}
				}, getString(R.string.attentionAlertDialogTitle),
				getString(R.string.internetConnectionSendMsgwAlertDialogMessage));
		newFragment.show(getSupportFragmentManager(), "dialog");
	}

	private void showDialog() {
		DialogFragment newFragment = MyAlertDialogFragment.newInstance(this,
				getString(R.string.attentionAlertDialogTitle),
				getString(R.string.deleteItemAlertDialogMessage));
		newFragment.show(getSupportFragmentManager(), "dialog");
	}

	@Override
	public void doPositiveClick() {
		int num = DatabaseHelperSingleton.getInstance(this).getDatabaseHelper()
				.deleteMsgwItem(msgw);
		if (num != 0)
			initData();
	}

	private void sendWebMessage() {
		if (ConnectivityInformationSingleton.getInstance(this)
				.getConnectivityInformation().isInternetConnectionAvailable()) {

			ContactActionControllerSingleton
					.getInstance(this)
					.getContactActionController()
					.sendMsgWebConnection(this, nombre,
							txtMensajeWeb.getText().toString(), false);
		} else
			showInternetConnectionDialog();
	}

	// Notifications

	private void showNotificationSending() {
		notification = new Notification(R.drawable.quick_action_msgweb_sending,
				getString(R.string.sendMsgwNotificationTitle),
				System.currentTimeMillis());

		PendingIntent contentIntent = PendingIntent.getActivity(
				getApplicationContext(), 0, new Intent(),
				PendingIntent.FLAG_UPDATE_CURRENT);

		notification.setLatestEventInfo(this,
				getString(R.string.sendingMsgwNotificationMessage),
				getString(R.string.sendMsgwNotificationTitle), contentIntent);

		notification.flags = Notification.FLAG_ONGOING_EVENT;

		notificationManager.notify(NOTIFICATION, notification);
	}

	private void updateNotificationSent() {
		Intent intent = new Intent(this, MsgwConversationListActivity.class);
		intent.putExtra("name", nombre);

		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				new Intent(this, HistorialLogFragmentActivity.class),
				PendingIntent.FLAG_UPDATE_CURRENT);

		notification.flags = Notification.FLAG_AUTO_CANCEL;
		notification.defaults |= Notification.DEFAULT_SOUND;

		notification.icon = R.drawable.quick_action_msgweb_sent_succes;
		notification.setLatestEventInfo(this,
				getString(R.string.sentMsgwNotificationMessage),
				getString(R.string.sendMsgwNotificationTitle), contentIntent);

		notificationManager.notify(NOTIFICATION, notification);
	}

	private void updateErrorNotificationSent() {
		PendingIntent contentIntent = PendingIntent.getActivity(
				getApplicationContext(), 0, new Intent(),
				PendingIntent.FLAG_UPDATE_CURRENT);

		notification.flags = Notification.FLAG_AUTO_CANCEL;
		notification.defaults |= Notification.DEFAULT_SOUND;

		notification.icon = R.drawable.quick_action_msgweb_sent_error;
		notification.setLatestEventInfo(this,
				getString(R.string.sentMsgwNotificationErrorMessage),
				getString(R.string.sendMsgwNotificationTitle), contentIntent);

		notificationManager.notify(NOTIFICATION, notification);
	}

	@Override
	public void doNegativeClick() {
	}

	@Override
	public void onSending() {
		showNotificationSending();
	}

	@Override
	public void onSuccess() {
		updateNotificationSent();
		finish();
	}

	@Override
	public void onError() {
		updateErrorNotificationSent();
	}
}
